<template>
  <div class="app-container">
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      size="small"
      label-width="80px"
    >
      <el-form-item
        label="姓名"
        prop="userName"
      >
        <el-input
          v-model="form.userName"
          style="width: 370px;"
        />
      </el-form-item>
      <el-form-item
        label="性别"
        prop="sex"
      >
        <el-input
          v-model="form.sex"
          style="width: 370px;"
        />
      </el-form-item>
    </el-form>
    <div class="detail-btn-group">
      <el-button type="primary" @click="saveDetail('form')">保存</el-button>
      <el-button type="text" @click="cancelForm">取消</el-button>
    </div>
  </div>
</template>
<script>
import { add, edit, findOne } from '../../../api/exercise/user.js'

export default {
  components: {},
  data() {
    return {
      id: '',
      form: {},
      rules: {
        userName: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        sex: [
          { required: true, message: '请输入性别', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.id = this.$route.params.id
    this.loadUser()
  },
  activated() {
    this.loadUser()
  },
  methods: {
    loadUser() {
      if (this.id) {
        const that = this
        findOne(this.id).then(res => {
          console.log(res)
          that.form = res
        }, err => {
          this.$message.warning(err)
        })
      } else {
        this.form = {}
      }
    },
    saveDetail(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.id) {
            edit(this.form).then(res => {
              this.$message.success('修改成功')
            }, err => {
              this.$message.warning(err)
            })
          } else {
            add(this.form).then(res => {
              this.$message.success('新增成功')
            }, err => {
              this.$message.warning(err)
            })
          }
        }
      })
    },
    cancelForm() {
      this.$router.push({ 'path': '/exercise2/user' })
    }
  }
}
</script>
